package com.china08.yxyapi.api.manage.sch.platform.website.article;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.sws.SwsSection;
import com.china08.yxyapi.entity.mg.sws.SwsArticle;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.SwsSectionRepository;
import com.china08.yxyapi.repository.mg.SwsArticleRepository;
import com.china08.yxyapi.util.HtmlCompressorUtil;
import com.china08.yxyapi.util.StringTrimUtil;

import io.swagger.annotations.ApiOperation;

@CrossOrigin
@RestController
public class ArticleCrtController extends YxyApiBaseController {

    @Autowired
    SwsSectionRepository swsSectionRepository;

    @Autowired
    SwsArticleRepository swsArticleRepository;

    @ApiOperation("添加资讯")
    @RequestMapping(value = "/api_yw/manage/sch/platform/website/article/crt", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object precess(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) {
        String title = reqModel.title;
        String author = reqModel.author;
        Date showDate = reqModel.showDate;
        String attachmentDownloadUrl = reqModel.attachmentDownloadUrl;
        String attachmentFileName = reqModel.attachmentFileName;
        String content = reqModel.content;
        String section1Id = reqModel.section1Id;
        String section2Id = reqModel.section2Id;
        String faceImg = reqModel.faceImg;

        String schoolId = getProfile(request, response).getSchoolId();
        String senderId = getProfile(request, response).getId();
        String senderName = getProfile(request, response).getUserNick();

        // 获取详情中的第一张图片作为推荐图片
        Document document = Jsoup.parse(content);
        Elements elements = document.select("img");
        if (elements.size() > 0) {
            faceImg = elements.get(0).attr("src");
        }
        content = HtmlCompressorUtil.HtmlCompressor(content);

        // 判断是否有二级栏目
        List<SwsSection> swsSection2List = swsSectionRepository.findBySchoolIdAndPidOrderByOrderNumAsc(schoolId, section1Id);
        // 有二级栏目，并且没有选择二级栏目
        if (StringUtils.isBlank(section2Id) && swsSection2List.size() > 0) {
            Assert.isTrue(false, "二级栏目不能为空");
        }
        if (null == showDate) {
            showDate = new Date(System.currentTimeMillis());
        } else {
            Calendar CD = Calendar.getInstance();
            int HOUR = CD.get(Calendar.HOUR_OF_DAY);
            int MINUTE = CD.get(Calendar.MINUTE);
            int SECOND = CD.get(Calendar.SECOND);
            showDate.setHours(HOUR);
            showDate.setMinutes(MINUTE);
            showDate.setSeconds(SECOND);
        }

        // 审核状态
        Integer AuditStatus = 0;

        // ###
        // 判断当前栏目是否需要审核，设置文章AuditStatus状态
        // 发送到二级
        if (StringUtils.isNotBlank(section2Id)) {
            SwsSection section = swsSectionRepository.findById(section2Id);
            Assert.isTrue(null != section, "二级栏目为空");
            AuditStatus = section.getIsAudit() ? 0 : 1;
        }
        // 发送到一级
        else {
            SwsSection section = swsSectionRepository.findById(section1Id);
            Assert.isTrue(null != section, "一级栏目为空");
            AuditStatus = section.getIsAudit() ? 0 : 1;
        }

        Integer orderNum = 1;
        // 获取排列序号
        SwsArticle swsArticle = swsArticleRepository.findTop1ByOwnerSchoolIdOrderByOrderNumDesc(schoolId);
        if (swsArticle != null) {
            orderNum = swsArticle.getOrderNum() + 1;
        }

        swsArticle = new SwsArticle();
        swsArticle.setId(UUID.randomUUID().toString().replace("-", ""));
        swsArticle.setAuthor(author);
        swsArticle.setSection1Id(section1Id);
        swsArticle.setSection2Id(section2Id);
        swsArticle.setTitle(title);
        swsArticle.setContent(content);
        swsArticle.setOwnerSchoolId(schoolId);
        swsArticle.setSenderId(senderId);
        swsArticle.setSenderName(senderName);
        swsArticle.setShowDate(showDate);
        swsArticle.setOrderNum(orderNum);
        swsArticle.setAuditStatus(AuditStatus);
        swsArticle.setAttachmentFileName(attachmentFileName);
        swsArticle.setAttachmentDownloadUrl(attachmentDownloadUrl);
        swsArticle.setFaceImg(faceImg);
        swsArticleRepository.save(swsArticle);
        return true;
    }

    protected static class ReqModel extends YxyApiReqModel {
        public String title;
        public String section1Id;
        public String section2Id;
        public String author;
        public Date showDate;
        public String attachmentFileName;
        public String attachmentDownloadUrl;
        public String content;
        public String faceImg;

        @Override
        public void autoCheck() {
            title = StringTrimUtil.trim(title);
            author = StringTrimUtil.trim(author);

            Assert.isTrue(StringUtils.isNotBlank(title), "标题不能为空");
            Assert.isTrue(title.length() > 1 && title.length() < 37, "请输入2-36个字的标题");
            Assert.isTrue(StringUtils.isNotBlank(section1Id), "一级栏目不能为空");
            Assert.isTrue(StringUtils.isNotBlank(content), "内容不能为空");
            if (StringUtils.isNotBlank(author)) {
                Assert.isTrue(author.length() < 7 && author.length() > 1, "作者要在2-6个字");
            }
        }
    }

    protected static class RespModel extends YxyApiRespModel {

    }
}
